package com.situ.admin.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.situ.admin.bean.Root;
import com.situ.admin.mapper.RootMapper;
import com.situ.admin.service.RootService;
import com.situ.admin.utils.MD5Util;

@Service
public class RootServiceImpl implements RootService {

	@Autowired
	private RootMapper rootMapper;

	@Override
	public Root login(Root root) throws Exception {
		// 1判断账号密码格式
		if (root.getRootname() == null || root.getRootname().length() < 3 || root.getRootname().length() > 16) {
			throw new Exception("账号格式不对");
		}
		if (root.getPassword() == null || root.getPassword().length() < 3 || root.getPassword().length() > 16) {
			throw new Exception("密码格式不对");
		}
		// 2查询账号信息
		Root selectroot = rootMapper.selectByRootName(root.getRootname());
		// 3判断是否存在
		if (selectroot == null) {
			throw new Exception("账号不存在");
		}
		// 4判断密码是否正确
		if (!selectroot.getPassword().equals(MD5Util.getMD5(root.getPassword()))) {
			throw new Exception("密码错误！！");
		}
		// 5判断账号是否可用
		if (selectroot.getStatus() != 0) {
			throw new Exception("账号被禁用！！");
		}
		// 6返回root
		return selectroot;
	}

	@Override
	public Root loginEdit(Root root) throws Exception {

		if (root.getPassword() == null || root.getPassword().length() < 3 || root.getPassword().length() > 16) {
			throw new Exception("旧密码格式不对");
		}
		if (root.getNewpassword() == null || root.getNewpassword().length() < 3
				|| root.getNewpassword().length() > 16) {
			throw new Exception("新密码格式不对");
		}
		if (root.getRealname() == null || root.getRealname().length() < 2 || root.getRealname().length() > 5) {
			throw new Exception("真实姓名码格式不对");
		}

		Root selectroot = rootMapper.selectByPrimaryKey(root.getId());
		if (!selectroot.getPassword().equals(MD5Util.getMD5(root.getPassword()))) {
			throw new Exception("旧密码不对");
		}
		if (!root.getNewpassword().equals(root.getRepassword())) {
			throw new Exception("新密码和确认密码不对");
		}
		;
		root.setPassword(MD5Util.getMD5(root.getNewpassword()));
		rootMapper.updateByPrimaryKey(root);
		return rootMapper.selectByPrimaryKey(root.getId());
	}

	@Override
	public Root getByRootName(String rootname) {
		return rootMapper.selectByRootName(rootname);
	}

}
